<template>
  <div class="container">
    <div class="top">
      <div class="title title-text">数据罗盘</div>
      <div class="compass">
        <div class="compass-item">
          <div class="compass-title">
            <div>我的小店</div>
            <div>
              <el-tooltip class="item" effect="dark" content="已入驻的小店数量(含小店和会员店)" placement="top">
                <img src="@/assets/images/icon/server-shop.png" alt="">
              </el-tooltip>
            </div>
          </div>
          <div class="compass-number">{{compassInfo.myShopNum}}</div>
          <div class="compass-bottom">昨日新增: {{compassInfo.shopYesterdayAddNum}}</div>
        </div>
        <div class="compass-item">
          <div class="compass-title">
            <div>我的乐粉</div>
            <div>
              <el-tooltip class="item" effect="dark" content="邀请乐粉数" placement="top">
                <img src="@/assets/images/icon/collection.png" alt="">
              </el-tooltip>
            </div>
          </div>
          <div class="compass-number">{{compassInfo.myMemberNum}}</div>
          <div class="compass-bottom">昨日新增: {{compassInfo.memberYesterdayAddNum}}</div>
        </div>
        <div class="compass-item">
          <div class="compass-title">
            <div>本月佣金预估收益</div>
            <div>
              <el-tooltip class="item" effect="dark" content="预估佣金收益，含淘客佣金及红包商城佣金" placement="top">
                <img src="@/assets/images/icon/bay-history.png" alt="">
              </el-tooltip>
            </div>
          </div>
          <div class="compass-number"><span class="rmb">￥</span>{{compassInfo.monthCommission}}</div>
          <div class="compass-bottom">上月已结算: ￥{{compassInfo.lastMonthCommission}}</div>
        </div>
        <div class="compass-item">
          <div class="compass-title">
            <div>本月服务收益预估</div>
            <div>
              <el-tooltip class="item" effect="dark" content="本月服务收益，含冻结中服务收益" placement="top">
                <img src="@/assets/images/icon/server-order.png" alt="">
              </el-tooltip>
            </div>
          </div>
          <div class="compass-number"><span class="rmb">￥</span>{{compassInfo.monthServiceIncome}}</div>
          <div class="compass-bottom">上月已结算: ￥{{compassInfo.lastMonthServiceIncome}}</div>
        </div>
      </div>
    </div>
    <div class="data-box">
      <div class="data-box-left" style="margin-right:10px">
        <div class="legend">
          <div class="slot"></div>
          {{ dataName }}
        </div>
        <span class="title-text">趋势概要</span>
        <el-date-picker
          class="date-piacker"
          v-model="rangeTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="mini"
          :picker-options="pickerOptions"
          @change="rangeTimeChange"
        />
        <span class="text">(默认近15天数据,最多选择30天)</span>
        <div class="summary-graph">
          <div class="tabs">
            <div class="tab-item" :class="{tab_active: type === 1}" @click="tabChange(1,'jStoreData', '小店新增')">
              小店新增
              <div v-show="type === 1" class="slot"></div>
            </div>
            <div class="tab-item" :class="{tab_active:  type === 2}" @click="tabChange(2,'fansData', '乐粉新增')">
              乐粉新增
              <div v-show="type === 2" class="slot"></div>
            </div>
            <div class="tab-item" :class="{tab_active:  type === 3}" @click="tabChange(3,'serviceData', '服务收益')">
              服务收益
              <div v-show="type === 3" class="slot"></div>
            </div>
            <div class="tab-item" :class="{tab_active:  type === 4}" @click="tabChange(4,'commissionData', '佣金收益')">
              佣金收益
              <div v-show="type === 4" class="slot"></div>
            </div>
          </div>
          <!-- <ve-histogram
            :data="checkedData"
            :extend="chartExtend"
            :settings="settings"
            :legend-visible="false"
          /> -->
          <ve-histogram :data="chartDatas" :settings="chartSettings"></ve-histogram>
          <!-- <el-tabs v-model="activeName" stretch>
            <el-tab-pane label="小店新增" name="first">
              <ve-histogram
                v-if="activeName === 'first'"
                :data="jStoreData"
                :extend="chartExtend"
              />
            </el-tab-pane>
            <el-tab-pane label="乐粉新增" name="second">
              <ve-histogram
                v-if="activeName === 'second'"
                :data="fansData"
                :extend="chartExtend"
              />
            </el-tab-pane>
            <el-tab-pane label="服务收益" name="third">
              <ve-histogram
                v-if="activeName === 'third'"
                :data="serviceData"
                :extend="chartExtend"
              />
            </el-tab-pane>
            <el-tab-pane label="佣金收益" name="fourth">
              <ve-histogram
                v-if="activeName === 'fourth'"
                :data="commissionData"
                :extend="chartExtend"
              />
            </el-tab-pane>
          </el-tabs> -->
        </div>
      </div>
      <div class="title data-box-right">
        <div class="rank-header">
          <div class="title-text">小店交易流水排名</div>
          <div class="rank-header-right">
            <div :class="{'time':true, 'active': timeType === 'yesterday'}" @click="timeTypeChange('yesterday')">日</div>
            <div :class="{'time':true, 'active': timeType === 'last_week'}" @click="timeTypeChange('last_week')">周</div>
            <div :class="{'time':true, 'active': timeType === 'last_month'}" @click="timeTypeChange('last_month')">月</div>
          </div>
        </div>
        <div>
          <ul>
            <li v-for="(item, index) in rankList" :key="item.count" class="rank-item">
              <span class="rank-num">{{ index + 1}}</span>
              <span class="rank-shop">{{ item.name}}</span>
              <span class="rank-count"><span>￥</span>{{ item.v}}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import { getProductList } from "@/api/goods";
import { getTrendData, getCompassData,trendingData,shopSaleRanking } from '@/api/home'
// import errorImg from "@/assets/images/icon/home-active.png";
export default {
  data() {
    const end = this.$moment().subtract(1, 'day').format('YYYY-MM-DD')
    const start = this.$moment().subtract(15, 'day').format('YYYY-MM-DD')
    return {
      compassInfo: {
        // shop_total: '', // 店铺总数
        // shop_increase: '', // 店铺昨日新增
        // fans_user_total: '', // 粉丝总数
        // fans_user_increase: '', // 粉丝昨日新增
      },
      rankInfo: {
        yesterday: [],
        last_week: [],
        last_month: []
      }, // 排名信息
      rankList: [],
      dataType: 'jStoreData',
      dataName: '小店新增',
      rangeTime: [start, end],
      timeType: 'yesterday',
      jStoreData: {
        columns: ['日期', '新增小店'],
        rows: []
      },
      fansData: {
        columns: ['日期', '新增乐粉'],
        rows: []
      },
      serviceData: {
        columns: ['日期', '服务收益'],
        rows: []
      },
      commissionData: {
        columns: ['日期', '佣金收益'],
        rows: []
      },
      checkedData: {
        columns: ['日期', '新增小店'],
        rows: []
      },
      settings: {
        legend: {
          show: false
        }
      },
      chartExtend: {
        series: {
            barWidth: 20,
            color: 'rgb(24, 144, 255)',
            label: {
              show: false
            }
        }
      },
      pickerOptions: {
        disabledDate(time) {
          return (time.getTime() + 3600 * 24 * 1000) > new Date().getTime()
        }
      },
      activeName: 'first',
      rank: [],
      type:1,

      chartDatas: {
        columns: ['日期', '新增小店'],
        rows: [
          // { '日期': '1月1日', '销售额': 123 },
          // { '日期': '1月2日', '销售额': 1223 },
          // { '日期': '1月3日', '销售额': 2123 },
          // { '日期': '1月4日', '销售额': 4123 },
          // { '日期': '1月5日', '销售额': 3123 },
          // { '日期': '1月6日', '销售额': 7123 }
        ]
      },
      chartSettings: {
        // 可选配置项
        xAxisType: 'category',
        yAxisType: 'value',
        itemStyle: {
          color: function(params) {
            // 你可以根据 params 参数来动态设置颜色
            // 这里使用一个简单的颜色数组
            const colors = ['#2361F1'];
            return colors[params.dataIndex % colors.length];
          }
        }
      }
    }
  },
  // watch: {
  //   // timeType(newValue) {
  //   //   console.log(newValue)
  //   //   this.rankList = this.rankInfo[newValue]
  //   // },
  //   // dataType(newValue) {
  //   //   this.checkedData = this[newValue]
  //   // }
  // },
  mounted() {
    const params = {
      start_time: this.rangeTime[0],
      end_time: this.rangeTime[1]
    }
    const paramss = {
      startTime: this.rangeTime[0],
      endTime: this.rangeTime[1]
    }
    // this.getDataTrend(params)
    this.getDataCompass()
    const today = new Date();
    let data={
      startTime : new Date(today.getTime() - (24 * 60 * 60 * 1000)),
      endTime : new Date()
    }
    this.getWeekData(data)

    this.getQushi(paramss)

  },
  methods: {
   getStartAndEndOfMonth(year, month) {
      // 注意：JavaScript 中的月份是从 0 开始计数的，所以传入的月份需要减 1
      const startDate = new Date(year, month - 1, 1);
      const endDate = new Date(year, month, 0);

      return {
        start: startDate,
        end: endDate
      };
    },


    getCurrentWeek () {
      const now = new Date();
      const dayOfWeek = now.getDay(); // 0-6, 0是周日
      const dayOfWeekMonday = dayOfWeek || 7; // 如果是周日，使用7
      const startDate = new Date(now);
      startDate.setDate(now.getDate() - (dayOfWeekMonday - 1));
      const endDate = new Date(now);
      endDate.setDate(now.getDate() + (7 - dayOfWeekMonday));

      return {
        start: startDate,
        end: endDate
      };
    },
    getWeekData(data){
   
      shopSaleRanking(data).then(res => {

        this.rankList = res.data
        // const data = res.data.map(item => {
        //   const dateArr = item.date.split('-')
        //   const date = dateArr[1] + '-' + dateArr[2]
        //   return {
        //     '日期': date,
        //     '新增小店': item.shop_increase,
        //     '新增乐粉': item.user_increase,
        //     '服务收益': Number(item.profit_service_predict),
        //     '佣金收益': Number(item.profit_commission_predict)
        //   }
        // })
        // this.jStoreData.rows = data
        // this.fansData.rows = data
        // this.serviceData.rows = data
        // this.commissionData.rows = data
        // this.checkedData = this[this.dataType]
      })
    },
    getQushi(paramss){
      const param = {
        type:this.type,
        ...paramss
      }
      trendingData(param).then(res => {

        this.checkedData = res.data
        
        if(this.type==1){
          this.chartDatas.columns=['日期', '新增小店']
        }
        if(this.type==2){
          this.chartDatas.columns=['日期', '新增乐粉']
        }
        if(this.type==3){
          this.chartDatas.columns=['日期', '服务收益']
        }
        if(this.type==4){
          this.chartDatas.columns=['日期', '佣金收益']
        }

        // chartDatas: {
        // columns: ['日期', '销售额'],
        //   rows: [
        //     { '日期': '1月1日', '销售额': 123 },
        //     { '日期': '1月2日', '销售额': 1223 },
        //     { '日期': '1月3日', '销售额': 2123 },
        //     { '日期': '1月4日', '销售额': 4123 },
        //     { '日期': '1月5日', '销售额': 3123 },
        //     { '日期': '1月6日', '销售额': 7123 }
        //   ]
        // },
       // if(res.data.length>0){
          const date=res.data.map(item=>{
          return {
            '日期': item.d,
            '新增小店': item.v,
            '新增乐粉': item.v,
            '服务收益': item.v,
            '佣金收益': item.v
              }
          })
          this.chartDatas.rows=date
       // }

        })
    },
    getDataTrend(params) {
      getTrendData(params).then(res => {
        const data = res.data.map(item => {
          const dateArr = item.date.split('-')
          const date = dateArr[1] + '-' + dateArr[2]
          return {
            '日期': date,
            '新增小店': item.shop_increase,
            '新增乐粉': item.user_increase,
            '服务收益': Number(item.profit_service_predict),
            '佣金收益': Number(item.profit_commission_predict)
          }
        })
        this.jStoreData.rows = data
        this.fansData.rows = data
        this.serviceData.rows = data
        this.commissionData.rows = data
        this.checkedData = this[this.dataType]
      })
    },
    getDataCompass() {
      getCompassData().then(res => {
        this.compassInfo = res.data
        console.log(res.data)
        // this.rankInfo = res.data.census_shop
        // this.rankList = this.rankInfo.yesterday
      })
    },
    // 搜索时间改变
    rangeTimeChange(dateArr) {
      if (this.$moment(dateArr[1]).valueOf() - this.$moment(dateArr[0]).valueOf() > 3600 * 24 * 29 * 1000) { // 超过30天
      this.$message.error('选择日期范围不超过30天！')
      } else {
        const params = {
          start_time: dateArr[0],
          end_time: dateArr[1]
        }
        const paramss = {
          startTime: dateArr[0],
          endTime: dateArr[1]
        }
        this.getDataTrend(params)
        this.getQushi(paramss)
      }
    },
    handleClick() {},
    tabChange(i,type, name) {
      this.type = i
        this.dataName = name
      const paramss = {
      startTime: this.rangeTime[0],
      endTime: this.rangeTime[1],
      type:i
      }
      this.getQushi(paramss)
      // this.dataType = type
      // this.dataName = name
      // this.checkedData = this[type]
    },
    timeTypeChange(type) {
      let startTime=''
      let endTime=''
      const today = new Date();

      let d = this.getCurrentWeek()

      // 获取当前月份的开始和结束日期

      const currentYear = today.getFullYear();
      const currentMonth = today.getMonth() + 1; // 因为月份是从 0 开始的，所以需要加 1

      const monthRange = this.getStartAndEndOfMonth(currentYear, currentMonth);
      // console.log('开始日期:', monthRange.start.toISOString().split('T')[0]);
      // console.log('结束日期:', monthRange.end.toISOString().split('T')[0]);

      console.log(d.start,this.$moment(d.start).format('YYYY-MM-DD'))
      switch (type) {
        case 'yesterday':
          startTime = new Date(today.getTime() - (24 * 60 * 60 * 1000))
          endTime = new Date()
          break;
        case 'last_week':
          startTime =d.start.toISOString().split('T')[0]
          endTime = d.end.toISOString().split('T')[0]
          break;
        case 'last_month':
          startTime = monthRange.start.toISOString().split('T')[0]
          endTime = monthRange.end.toISOString().split('T')[0]
          break;
      }
            // last_month
            // last_week
            // yesterday
      this.timeType = type
      let data={
        startTime:startTime,
        endTime:endTime
      }
      this.getWeekData(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: calc(100vh - 43px);
  background-color: #F3F7FF;
  .top {
    background-color: #fff;
    border-radius:10px 10px 0px 0px;
    padding: 20px 30px 35px 30px;
  }
  .title {
    .text {
      color: #333;
      font-weight: normal;
      font-size: 14px;
    }
  }
  .title-text {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }
  .compass {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    .compass-item {
      height: 248px;
      border-radius: 5px;
      padding: 20px;
      position: relative;
      box-shadow:0px 10px 20px 0px rgba(0, 0, 0, 0.15);
      border-bottom: 4px #2361F1 solid;
      margin-right: 17px;
      &:last-child {
      margin-right: 0px;
      }
      flex: 1;
      .compass-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #333333;
        font-size: 16px;
        margin-bottom: 20px;
        img {
          width: 24px;
          height: 24px;
        }
      }
      .compass-number {
        color: #333;
        font-size: 42px;
        font-weight: bold;
        font-family:DIN;
        .rmb {
          font-size: 24px;
        }
      }
      .compass-bottom {
        border-top: 1px #D7D7D7 solid;
        position: absolute;
        bottom: 20px;
        padding-top: 20px;
        width: calc(100% - 43px);
        color: #333333;
        font-size: 16px;
      }
    }
  }
  .date-piacker {
    margin: 0 10px;
  }
  .summary-graph {
    margin-top: 20px;
    // ::v-deep .el-tabs__item {
    //   padding: 0 50px 0 80px;
    //   &:first-child {
    //     padding-left: 20px;
    //   }
    // }
  }
  .data-box {
    display: flex;
    margin-top: 10px;
    height: calc(100vh - 470px);
    position: relative;
    .data-box-left {
      background-color: #fff;
      border-radius:0px 0px 0px 10px;
      flex: 1;
      padding: 24px 24px 0 24px;
      position: relative;
      .legend {
        position: absolute;
        display: flex;
        right: 37px;
        top: 100px;
        align-items: center;
        .slot {
          width: 24px;
          height: 4px;
          border-radius: 2px;
          background-color: #2361F1;
          margin-right: 5px;
        }
      }
      .tabs {
        display: flex;
        .tab-item {
          margin-right: 36px;
          color: #656565;
          font-size: 16px;
          display: flex;
          flex-direction: column;
          align-items: center;
          cursor: pointer;
        }
        .tab_active {
          font-weight: bold;
          color: #333333;
        }
        .slot {
          margin-top: 5px;
          width: 24px;
          height: 4px;
          border-radius: 2px;
          background-color: #2361F1;
        }
      }
    }
    .data-box-right {
      width: 450px;
      background-color: #fff;
      border-radius:0px 0px 10px 0px;
      padding: 24px 24px 0 24px;
    }
  }
  .rank-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .rank-header-right {
      display: flex;
      justify-content: space-between;
      .time {
        width: 30px;
        height: 30px;
        border: 1px solid #c9c9c9;
        border-radius: 5px;
        font-weight: normal;
        font-size: 16px;
        margin-left: 10px;
        text-align: center;
        line-height: 30px;
        cursor: pointer;
      }
      .active {
        background-color: #2361F1;
        color: white;
      }
    }
  }
  .rank-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .rank-num {
      background-color: rgba(51,51,51,0.1);;
    }
    &:nth-child(-n+3) {
      .rank-num {
        background-color: #333333;
        color: #fff;
      }
    }
  }
  .rank-num {
    display: inline-block;
    height: 28px;
    width: 28px;
    color: #333;
    line-height: 26px;
    text-align: center;
    border-radius: 50%;
    margin-right: 15px;
  }
  .rank-count {
    font-weight: bold;
    font-size: 18px;
    span {
      font-size: 10px;
    }
  }
  .rank-shop {
    flex: 1;
    color: #333333;
  }
}
</style>
